# -*- coding: utf-8 -*-

import os
import logging
import urllib2
from configobj import ConfigObj

class LibrarythingClient():
    def __init__(self):
        logging.info("Creating wrapper")
        config = ConfigObj('conf/pyBook.conf')
        self.url = config['lib_url']
        self.dir = config['covers_dir']


    def get_cover_by_isbn(self, isbn):
        complete_url = self.url + isbn
        file_name = self.dir + isbn
        if not os.path.isfile(file_name):
            data = urllib2.urlopen(complete_url)
            cover = file( file_name, "wb" )
            cover.write(data.read())
            cover.close()

        return file_name

    def get_cover(self, book):
        """
        Gets a cover from LibraryThing a returns it file name.
        """
        book.set_pixmap(self.get_cover_by_isbn(book.get_isbn()))


    def get_all_covers(self, book_list):
        for book in book_list:
            self.get_cover(book.get_isbn())
